package com.dyrnq.seckill.config;

import com.dyrnq.seckill.filter.ApiKeyFilter;
import com.dyrnq.seckill.filter.JwtFilter;
import com.dyrnq.seckill.interceptor.GlobalInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new GlobalInterceptor()).excludePathPatterns("/api/**");
    }

    /**
     * 用于压测API
     *
     * @param key
     * @return
     */
    @Bean
    @ConditionalOnProperty(
            value = "app.api-management.enabled",
            havingValue = "true")
    public FilterRegistrationBean<ApiKeyFilter> apiKeyFilter(@Value("${app.api-management.key}") String key) {
        FilterRegistrationBean<ApiKeyFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new ApiKeyFilter(key));
        registrationBean.addUrlPatterns("/api/*");
        registrationBean.setOrder(1);
        return registrationBean;
    }

    /**
     * 用于web网页用户登录，如果ApiKeyFilter通过了，则JwtFilter直接跳过
     *
     * @return
     */

    @Bean
    public FilterRegistrationBean<JwtFilter> jwtFilter(@Value("${app.jwt.secret}") String jwtSecret) {
        FilterRegistrationBean<JwtFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new JwtFilter(jwtSecret));
        registrationBean.addUrlPatterns("/api/*");
        registrationBean.setOrder(2);
        return registrationBean;
    }

}